package com.apobates.forum.orize.servlet;

import com.apobates.forum.orize.core.OrizeAnnotationScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;

/**
 * ServletContextListener实现类并生成资源文件
 * 参数:context-param
 *      orizeAnnoClass: OrizeAnnotationScanner的子类
 *      orizeAnnoPackage: 扫描Orize注解的基础包名
 * @author xiaofanku@live.cn
 * @since 20210822
 */
public class OrizeServletContextListener implements ServletContextListener {
    private final static Logger logger = LoggerFactory.getLogger(OrizeServletContextListener.class);
    private final static String TMP_ANNO_SC_KEY="__orizeAnnoFileName";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //是否使用了注解生成资源定义
        String orizeAnnoClass = sce.getServletContext().getInitParameter("orizeAnnoClass");
        String orizeAnnoBasePage = sce.getServletContext().getInitParameter("orizeAnnoPackage");
        if(null == orizeAnnoClass || null == orizeAnnoBasePage){
            return;
        }
        //构造实现实例
        OrizeAnnotationScanner oas = null;
        try {
            Class<OrizeAnnotationScanner> mqc = (Class<OrizeAnnotationScanner>) Class.forName(orizeAnnoClass).asSubclass(OrizeAnnotationScanner.class);
            oas = mqc.getDeclaredConstructor().newInstance();
        }catch (Exception e){
            if(logger.isDebugEnabled()){
                logger.debug("OrizeAnnotationScanner impl class instance fail");
            }
        }
        //扫描并保存
        try{
            String annoResName = oas.scanAndSave(orizeAnnoBasePage, sce.getServletContext().getRealPath("/WEB-INF/"));
            sce.getServletContext().setAttribute(TMP_ANNO_SC_KEY, annoResName);
        }catch (NullPointerException | IllegalStateException e){
            if(logger.isDebugEnabled()){
                logger.debug(e.getMessage(), e);
            }
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        String tmpResFileName = sce.getServletContext().getAttribute(TMP_ANNO_SC_KEY).toString();
        if(null!=tmpResFileName){
            //删除
            try {
                File tmpResFile = new File(sce.getServletContext().getRealPath("/WEB-INF/") + tmpResFileName);
                tmpResFile.deleteOnExit();
            }catch (Exception e){
                if(logger.isDebugEnabled()){
                    logger.debug(e.getMessage(), e);
                }
            }
        }
    }
}
